package com.googlecode.tidej.client;

import java.io.IOException;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.googlecode.tidej.client.util.Json;
import com.googlecode.tidej.client.util.LocalStorage;


/**
 * Global meta data. Don't keep in memory
 * to avoid issues with multiple browser windows.
 */
public final class PersistentState extends JavaScriptObject{
  
  static final String FILE_NAME = "tidej.state";
  
  public static PersistentState load() {
    String raw;
    try {
      raw = LocalStorage.getItem(FILE_NAME);
      return create(raw);
    } catch(Exception e) {
      return create();
    }
  }
  
  private static PersistentState create(String json) {
    return (PersistentState) Json.parseToObject(json);
  }

  private static native PersistentState create() /*-{
    return {};
  }-*/;

  
  protected PersistentState() {
  }

  public native String getLastOpened() /*-{
    return this['lastOpened'];
  }-*/;

  public native void setLastOpened(String s) /*-{
    this['lastOpened'] = s;
  }-*/;

  public String toJson() {
    StringBuilder sb = new StringBuilder("{lastOpened:'");
    sb.append(getLastOpened());
    sb.append("'}\n");
    return sb.toString();
  }
  
  public void save() throws IOException {
    LocalStorage.setItem(FILE_NAME, toJson());
  }
}
